﻿using System;
using System.IO;
using System.Reflection;
using Microsoft.WowAddonStudio.Lua.Model;
using Microsoft.WowAddonStudio.Lua.Support;
using Microsoft.WowAddonStudio.Lua.Tools.XmlDoc.Converters;
using Microsoft.WowAddonStudio.Lua.Tools.XmlDoc.Resources;

namespace Microsoft.WowAddonStudio.Lua.Tools.XmlDoc
{
    class Program
    {
        private static readonly XmlDocumentationSerializer serializer = new XmlDocumentationSerializer();

        static void Main(string[] args)
        {
            Console.WriteLine(Strings.XmlDocHeader);
            Console.WriteLine(Strings.AddOnStudioUrl);
            Console.WriteLine();

            if (args.Length == 0)
            {
                Console.WriteLine(Strings.RequiredParameterMissingFormat, "inputfile");
                Console.WriteLine(Strings.XmlDocUsageFormat, Path.GetFileName(Assembly.GetEntryAssembly().CodeBase));
                return;
            }
            if (!File.Exists(args[0]))
            {
                Console.WriteLine(Strings.FileDoesNotExistFormat, args[0]);
                return;
            }

            var inputFile = args[0];
            var outputFile = args.Length > 1 ? args[1] : Path.GetFileNameWithoutExtension(inputFile) + ".xml";

            Documentation documentation;

            switch(Path.GetExtension(inputFile))
            {
                case ".lua":
                    documentation = LuaConverter.ReadLuaDocumentation(inputFile);
                    break;
                case ".toc":
                    documentation = TocLoader.LoadTocDocumentation(inputFile);
                    break;
                default:
                    Console.WriteLine(Strings.InputUnsupported);
                    return;
            }

            using (var stream = File.Open(outputFile, FileMode.Create, FileAccess.Write))
                serializer.Serialize(stream, documentation);
        }
    }
}
